package com.finger.forest.service;


import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.finger.forest.base.CommonKey;
import com.finger.forest.listener.GpsLocationListener;
import com.finger.forest.utils.encode.PrefsUtil;

public class GpsService extends Service {

    private static final String TAG = "GpsService";

    // 2000ms
    private static final long minTime = 2000;
    // 最小变更距离 10m
    private static final float minDistance = 1;

    private LocationManager locationManager;
    private LocationListener locationListener;

    //service bind with activity.
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "GPS获取位置服务启动");
        super.onCreate();
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.ACCESS_FINE_LOCATION};

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "GPS获取位置服务开始");
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        String userId = PrefsUtil.getString(getApplicationContext(), CommonKey.USER_ID);
        String patrolId = PrefsUtil.getString(getApplicationContext(), CommonKey.PATROL_ID);
        locationListener = new GpsLocationListener(userId, patrolId);

        int permission = ActivityCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_FINE_LOCATION);
        /*if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }*/

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance,
                locationListener);
        return super.onStartCommand(intent, flags, startId);
    }

    //销毁service
    @Override
    public void onDestroy() {
        Log.i(TAG, "GPS获取位置服务停止");
        // TODO Auto-generated method stub
        super.onDestroy();
    }




}